﻿using DreamSpace.Net.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DreamSpace.Net
{
    /// <summary>
    /// This module implements a URI management object.
    /// URIs are used to identify a name or resource (URNs or URLs).
    /// </summary>
    public partial class URIExt : DSSExtension
    {
        public override string TypeNameSpace { get { return this.GetType().Namespace; } }
        public override string TypeName { get { return this.GetType().Name; } }

        UriBuilder _UriBuilder;

        public string OriginalString { get; set; }

        public string Scheme { get { return _UriBuilder.Scheme; } set { _UriBuilder.Scheme = value; } }
        public string Host { get { return _UriBuilder.Host; } set { _UriBuilder.Host = value; } }
        public int Port { get { return _UriBuilder.Port; } set { _UriBuilder.Port = value; } }
        public string Path { get { return _UriBuilder.Path; } set { _UriBuilder.Path = value; } }
        public string Query { get { return _UriBuilder.Query; } set { _UriBuilder.Query = value; } }

        public Uri Uri { get { return _UriBuilder.Uri; } }

        public bool IsLocalHost { get { return Uri.IsLoopback; } }
        public bool IsDefaultPort { get { return Uri.IsDefaultPort; } }
        public bool IsUnc { get { return Uri.IsUnc; } }

        public URIExt(string uriString)
        {
            OriginalString = uriString;
            _UriBuilder = new UriBuilder(uriString);
        }
        public URIExt(Uri uri)
        {
            OriginalString = uri.ToString();
            _UriBuilder = new UriBuilder(uri);
        }

        public URIExt Append(object path)
        {
            var _path = (path != null ? path.ToString() : "").Replace('\\', '/');

            if (!_path.EndsWith("/"))
                _path += "/";

            if (_UriBuilder.Path.EndsWith("/"))
            {
                if (_path.StartsWith("/"))
                    _UriBuilder.Path += _path.Substring(1);
                else
                    _UriBuilder.Path += _path;
            }
            else
            {
                if (_path.StartsWith("/"))
                    _UriBuilder.Path += _path;
                else
                    _UriBuilder.Path += "/" + _path;
            }

            return this;
        }
    }
}
